package com.wechat.page.login;

import com.swak.fx.support.AbstractComp;
import com.swak.fx.support.AbstractPage;
import com.swak.fx.support.Display;
import com.swak.fx.support.FXMLView;
import com.swak.fx.support.ui.UIButton;
import com.swak.fx.support.ui.UIImage;
import com.wechat.login.LoginService;
import com.wechat.page.property.LoginProperty;

import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

/**
 * 
 * 用户登录
 * 
 * @author 618lf
 */
@FXMLView(title = "用户登录", value = "UserLoginComp.fxml", css = "UserLoginComp.css", stageStyle = "TRANSPARENT")
public class UserLoginComp extends AbstractComp {

	@FXML
	private UIImage image;
	@FXML
	private Label name;
	@FXML
	private UIButton loginBtn;
	@FXML
	private Text switchBtn;
	@FXML
	private Pane divideBtn;
	@FXML
	private Text createBtn;
	@FXML
	private Pane placeholder;

	private final LoginProperty loginProperty = new LoginProperty();

	public UserLoginComp(AbstractPage parent) {
		super(parent);
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.image.image(Display.logo());
		this.loginBtn.Success().setText("登录");
	}

	@Override
	public void setupEventHandlers() {
		super.setupEventHandlers();
		this.switchBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			this.$emitInPage("page:switch");
		});
		this.createBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			this.$emitInPage("page:register");
		});
		this.loginBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			this.loginBtn.setText("登录中...");
			this.loginBtn.setDisable(true);
			this.$emitInPage("login");
		});
	}

	@Override
	public void setupBindings() {
		super.setupBindings();
		this.name.textProperty().bind(this.loginProperty.getNickNameProperty());
		this.image.nodeProperty().bind(Bindings.createObjectBinding(() -> {
			byte[] imageData = this.loginProperty.getHeadimgProperty().get();
			return imageData != null ? imageData : Display.logo();
		}, this.loginProperty.getHeadimgProperty()));
	}

	@Override
	public void setupValueChangedListeners() {
		super.setupValueChangedListeners();
	}

	@Override
	public void initializeFinish() {
		super.initializeFinish();
		try {
			LoginService.me().user();
		} catch (Exception e) {
			this.exitWithError(e);
		}
	}

	@Override
	public void activated() {
		super.activated();
	}
}